import { bulletFrequency, bulletSpeed } from "../../config.js";
import { randomColor } from "../../utils/randomColor.js";
import {
  boxW,
  currentState,
  domg,
  role1,
  role2,
  roleH,
  roleW,
} from "../../index.js";
import { getPosition } from "../newTransfrom.js";
import { scoket } from "../../utils/scoket.js";

const createBullet = (point: { x: number; y: number }, direction: number) => {
  const bullel = document.createElement("div");
  bullel.classList.add("bullet");
  bullel.style.transform = `translate(${point.x}px,${point.y}px)`;
  bullel.style.backgroundColor = randomColor();
  let timer: any = -1;
  domg("#app").appendChild(bullel);
  //#region 开启定时器每秒移动并判断情况
  timer = setInterval(() => {
    const position = getPosition(bullel);
    //判断是否进入边界
    if (position.x + 10 > boxW || position.x - 10 < 0) {
      position.x = boxW;
      bullel.remove();
      clearInterval(timer);
    }
    position.x += bulletSpeed * direction;
    bullel.style.transform = `translate(${position.x}px,${position.y}px)`;
  }, 100);
  //#endregion
};

scoket.$on((res) => {
  if (res.path === "/fire/j") {
    if (res.role === "p1") {
      fire(role1, 1);
    }
    if (res.role === "p2") {
      fire(role2, -1);
    }
  }
});

let timer: any;
export const fire = function (ele: HTMLElement, _dire?: number) {
  let direction = _dire || (currentState.role === "p1" ? 1 : -1);
  //及时响应操作
  if (typeof timer === "number") return;
  //判断这个函数是玩家调用的还是服务器返回的来决定是否发送请求
  _dire ||
    scoket.$emit({ role: currentState.role, path: "/fire/j", value: {} });

  //#region 创建子弹
  const rolePosition = getPosition(ele);
  const firePoint = {
    //子弹需要生成的位置
    x: rolePosition.x + direction * roleW,
    y: rolePosition.y + roleH / 2,
  };
  createBullet(firePoint, direction);
  //#endregion

  //控制子弹发射频率
  timer = setTimeout(() => {
    timer = undefined;
  }, 1000 / bulletFrequency);
};
